/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package replica;

import generalResourceLalla.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import replica.communication.MessageDispatcherReplicaHost;
import replica.transaction.ReplicaManager;
import replica.transaction.FrontEnd;
import replica.ReplicaDescriptor;
import org.xml.sax.SAXException;
import replica.communication.JMSAdapter;
import replica.communication.JMSAdapterReplicaManager;
import replica.stableMemory.StableFile;
import replica.transaction.TransactionStatus;

/**
 *
 * @author Elena
 */
public class ReplicaHostCreator 
{
    
    public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException
    {
        ReplicaLoggerFactory.cleanHostLogFolder();
        Utilities.emptyFolders("files/LogRegister/");
        Utilities.emptyFolders("files/ImageQueue/");
        Utilities.emptyFolders("files/logs/replica/");
       
        
        List<Long> replicaHosts=Utilities.convert(CostantiReplica.replicaHostIds);
        //List<Long> replicaHosts=askReplicaHostIdsToUser();
        
        NetworkParser n = new NetworkParser(Costanti.configurationFile);
        
        List<ReplicaDescriptor> nodes=n.getReplicaDescriptors();

        for (Long replicaHostId:replicaHosts)
            createSingleReplicaHost(replicaHostId,nodes);
    
        

    }

    
    //NON E' PIU' USATO, ERA TROPPO SCOMODO
    public static List<Long> askReplicaHostIdsToUser()
    {
        Scanner scanner = new Scanner(System.in);
        String token = null;

        List<Long> replicaHosts=null;
        while (replicaHosts == null) {
            try {
                replicaHosts = new LinkedList<Long>();
                System.out.print("\nPlease, insert the ids of virtual replicaHosts you want to"
                        + " instantiate on this machine. An axample of list is 1,4,7,8\n\t\t>>");
                String listString = scanner.next();
                StringTokenizer st = new StringTokenizer(listString, " ,");
                while (st.hasMoreTokens()) {
                    token = st.nextToken();
                    long id = Long.parseLong(token);
                    replicaHosts.add(id);
                }
            } catch (NumberFormatException nfe) {
                System.err.println("Error. number format exception in token " + token);
                replicaHosts = null;
            }
        }
        return replicaHosts;

    }
    
    public static void createSingleReplicaHost(
            long replicaHostId,List<ReplicaDescriptor> nodes) 
            throws IOException, ParserConfigurationException, SAXException
    {
        List<ReplicaManager> managers = new LinkedList();
        
        for (ReplicaDescriptor r : nodes) 
        {
            JMSAdapterReplicaManager jms = new JMSAdapterReplicaManager(r.getNodeId(),replicaHostId);
            ReplicaQueue queue = new ReplicaQueue(r.getNodeId(),replicaHostId,r.getCapacity());
            PendingTransactionStatusQueue statuses = new PendingTransactionStatusQueue();
            ReplicaManager f = new ReplicaManager(replicaHostId, r,jms,queue, statuses);
            Thread t = new Thread(f);
            t.start();         
            
            ReplicaKiller killer= new ReplicaKiller(t,f);
            Thread t2=new Thread(killer);
            t2.start();
            
            managers.add(f);
        }

        MessageDispatcherReplicaHost dispatcher = new MessageDispatcherReplicaHost(managers);
    }
    
    public static TaskList retrieveList(long replicaHostId, long NodeId)
    {
        StableFile<TaskList> stableFile=new StableFile<TaskList>("files/ImageQueue/queue_"+replicaHostId+"_"+NodeId+"/");
        TaskList list=stableFile.read(TaskList.class);
        return list;
        
    }
    
    public static TransactionStatus retrieveTransactionStatus(long replicaHostId, long NodeId)
    {
        StableFile<TransactionStatus> stableFile=new StableFile<TransactionStatus>("files/LogeResister/ReplicaManager_"+NodeId+"_"+replicaHostId+"/");
        TransactionStatus status=stableFile.read(TransactionStatus.class);
        return status;
                 
    }
    
}
